<template>
  <div class="article-list">
    <!-- 文章列表组件 -->
    <!-- 文章列表组件 -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :success-text="refreshSuccessText" :success-duration="1000" :animation-duration="1000">
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <!-- <van-cell v-for="(article,index) in articles" :key="index" :title="article.title" /> -->
            <article-item v-for="(article,index) in articles" :key="index" :title="article.title" :article="article"/>
        </van-list>
      </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item/"
export default {
  name: "ArticleList",
  components:{
    ArticleItem
  },
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      articles: [], //数据列表
      loading: false, //控制加载中的loding状态
      finished: false, //控制加载结束的状态
      timestamp: null, //当前时间搓
      count: 0,
      isLoading: false,//控制下拉刷新结束的状态
      refreshSuccessText:''//下拉刷新成功的提示文本
    };
  },
  methods: {
    //1.调用接口获取频道数据
    async onLoad() {
      const { data } = await getArticles({
        channel_id: this.channels.id, //频道id
        timestamp: this.timestamp || Date.now(), //时间戳，请求最新数据传当前时间戳，请求历史数据传指定时间戳。
        with_top: 1 //是否包含置顶项，1是包含，0是不包含
      });
      console.log(data);
      //2.把数据放到articles数组里面
      const { results } = data.data;
      this.articles.push(...results);
      //3.设置loding状态为结束，这样才能让它判断下一次是否需要加载
      this.loading = false;

      // 4.数据全部加载完成
      if (results.length) {
        this.timestamp = data.data.pre_timestamp;
      } else {
        this.loading = true;
      }
    },
    async onRefresh(){
        const { data } = await getArticles({
            channel_id: this.channels.id, 
            timestamp:Date.now(), 
            with_top: 1 
        });
       const { results } = data.data;
        this.articles.unshift(...results);
        this.isLoading = false;
        this.refreshSuccessText = `更新了${results.length}条数据`
    }
  }
};
</script>

<style lang="less" scoped>
.article-list {
  position: fixed;
  top: 90px;
  bottom: 50px;
  left: 0;
  right: 0;
  overflow-y: auto;
}
</style>